package news;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NewsDao {
	// findALL,add,delete,update方法

	public List<News> findALL() {
		String sql = "SELECT * FROM `news`;";
		Connection conn = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<News> list = new ArrayList();
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				News news = new News();
				news.setNid(rs.getInt("nid"));
				news.setNtid(rs.getInt("ntid"));
				news.setNtitle(rs.getString("ntitle"));
				news.setNauthor(rs.getString("nauthor"));
				news.setNcreateDate(rs.getDate("ncreateDate"));
				news.setNpicPath(rs.getString("npicPath"));
				news.setNcontent(rs.getString("ncontent"));
				news.setNmodifyDate(rs.getDate("nmodifyDate"));
				news.setNsummary(rs.getString("nsummary"));
				list.add(news);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(rs, ps, conn);
		}
		return list;
	}

	public int add(News n) {
		String sql = "INSERT INTO news(ntid,ntitle,nauthor,ncreateDate,npicPath,ncontent,nmodifyDate,nsummary) VALUES(?,?,?,?,?,?,?,?);";
		return DBUtil.executeUpdate(sql, n.getNtid(), n.getNtitle(),
				n.getNauthor(), n.getNcreateDate(), n.getNpicPath(),
				n.getNcontent(), n.getNmodifyDate(), n.getNsummary());
	}

	public int del(int nid) {
		String sql = "DELETE FROM news WHERE nid=?;";
		return DBUtil.executeUpdate(sql, nid);
	}

	public int update(News n) {
		String sql = "UPDATE news SET ntid=?,ntitle=?,nauthor=?,ncreateDate=?,npicPath=?,ncontent=?,nmodifyDate=?,nsummary=? WHERE nid=?;";
		return DBUtil.executeUpdate(sql, n.getNtid(), n.getNtitle(),
				n.getNauthor(), n.getNcreateDate(), n.getNpicPath(),
				n.getNcontent(), n.getNmodifyDate(), n.getNsummary(),
				n.getNid());
	}
}